DScaler Coding Standards
á

The Deinterlace Project - Revision 1.0

Abstract:

This document describes the C++ Coding Standards as they are used in the deinterlace project. It provides a set of guidelines, rationales and standards for C/C++ coding.

Copyright notice

Deinterlace Copyright (c) 2001 John Adcock

Revision 1.6 , Last Modified: 2001/07/13

This material may be distributed only subject to the terms and conditions set forth in the Open Publication License.

This document was based on the on the CoreLinux C++ Coding standards document version 1.6

The original document can be found http://corelinux.sourceforge.net/cppstnd.php

CoreLinux++ Copyright (c) 1999, 2000 CoreLinux Consortium

Revision 1.6 , Last Modified: 2000/09/22

This material may be distributed only subject to the terms and conditions set forth in the Open Publication License.

Scope

The principle function of this document is to establish a consistent standard which will provide for easier maintenance of code. This will benefit the team and the project in that those who are new to the code can quickly orient themselves, and thereby sooner become productive members of the team. It is intended to be a dynamic document and can be reviewed as needed. It is recommended that each programmer keep a copy on hand also.

Document Overview

The following document sections contain standards, guidelines, and rationales. Guidelines must be adhered to unless there is compelling reason to deviate. Deviation from a guideline must be discussed and approved during the code walk-through. A standard is an item to which compliance is mandatory. Deviation from a standard must be discussed, approved, and signed-off on by the team lead during the code walk-through. Rationales have been used where necessary to explain the meaning of an item, or why it was chosen.

General Principles

This section contains the basic philosophy a developer should keep in mind while coding.

Comments

This section deals with the placement and contents of comments in the code.

Code Layout

This section has to do with the alignment of the code, white space, declarations and keywords, and where they should all be located.

Naming Conventions

This section contains the structure for naming classes, functions, files, and directories.

Usage

This section concerns the 'how' and 'when' certain constructs should be used (for example, loops, inheritance, error handling, etc.)

File Layout

This section applies to where things should be located in header files and modules.

General Principles

The primary goal of the coding standard is maintainability. Other important considerations that relate to the spirit of the standard are correctness, readability, consistency, extensibility, portability, clarity, and simplicity. When in doubt, the programmer should strive for clarity first, then efficiency.

Think of the reader. Do not just write for yourself. Keep it simple. Break down complexity into simpler chunks. Clearly comment necessary complexity. Be explicit. Avoid implicit or obscure language features. Be consistent. Minimize scope, both logical and visual.

Much of the code in DScaler does not conform to these standards. Please when making changes try to apply the standards to any surrounding code. This is especially true of comments and variable naming.

Comments

Guideline 1: Be clear and concise. Say what is happening and why. Do not restate code.

Guideline 2: Keep code and comments visually separate.

Standard 1: Use top of file comments for all files. Include CVS $Id$ and $Log$ tags on this block. Include the correct GPL comment and assign copyright to yourself for totally new files or the same as the original source if splitting files.

Standard 1: Use only the C++ comment style (double slashes) for single line comments.

Guideline 3: For block comment styles either C++ (double slashes) or C style (/* ... */) can be used.

// ...

-OR-

/* ... */

Guideline 4: Prefer block comments over trailing comments. Use block comments regularly. Only use trailing comments for special items.

Standard 5: Trailing comments must all start in the same column in the function.

Standard 6: Trailing comments at a closing brace are indented one level from brace.

Standard 7: Block comments are at the same indentation level as the block they describe.

Standard 8: Ensure comments are correct (and stay correct).

á

Code Layout

Guideline 5: Write code in a series of chunks.

Guideline 6: Use block comments to separate the chunks.

Standard 9: Put one statement per line, except with in-line code in a header file.

Guideline 7: Functions shall have a single exit point. Exceptions to this rule are allowed in simple cases (e.g. where functions are less than 15 lines) and for invalid parameter checks.

Rationale: Multiple exit points usually add to the complexity of a function.

Standard 10: Indentation level is four (4) spaces. Set editor to replace tabs with spaces

á

Braces and Parenthesis

Standard 11: Braces shall be aligned using Ulman style where the braces are at the same scope as the statement that proceeds them and the code within the braces is indented one level. Braces are always on a line by themselves.

void DoSomething( void )
{
    if(x != y)
    {
        y = x;
    }
    else
    {
        ; // do nothing
    }
}

-NOT-

void DoSomething( void )
{
    if(x != y)
    {
    y = x; // should be indented
    }
    else
    {
    ; // do nothing
    }
}

- OR -

void DoSomething( void )
{
    if(x != y)
        { // brace is not the same scope
        y = x;
        }
    else
        {
        ; // do nothing
        }
}

- OR -

void DoSomething( void )
{
    if(x != y){ // brace is not on a line by itself
        y = x;
    }
    else{
        ; // do nothing
    }
}

Standard 12: While, for and if statements shall always use braces, even if they are not syntactically required.

Guideline 8: Use parenthesis to group within a statement and to emphasize evaluation order.

Guideline 9: Avoid unnecessary parentheses.

Guideline 10: Avoid deep (more than three) levels of parenthesis nesting.

Declarations

Standard 14: Start each declaration on a new line. (Except for loops where the counter can be defined within the statement)

Standard 15: Enumeration declarations will be declared with named constants in upper case and the identifier specified as described in Naming conventions. Where it is expected that code will iterate over the space defined by the enum then there should be a ???_LAST_ONE entry defined.

enum eIdentifier
{
    ONE,
    TWO,
    THREE
};

- or -

á
enum eIdentifier
{
    ONE = 1,
    TWO,
    THREE,
    IDENTIFIER_LAST_ONE,
};

Standard 16: All variables must be initialized.

Guideline 11: Use vertical alignment to ease scanning of declarations. Where possible the variable names should start in column 15.

STRING         StringToUse;
int            MyInt;
COMPLEX        ComplexNumberToUse;

-instead of-

STRING StringToUse;
int MyInt;
COMPLEX ComplexNumberToUse;

Standard 17: Do not create anonymous types (structs), except in a class declaration where a private structure is declared.

Keyword Constructs

Standard 19: Nested else if statements shall be indented as normal statements, the if shall appear on the same line as the else, and shall have a final else statement (most likely with a NEVER_GET_HERE; statement).

á
if( x > y )
{
    x = x - y;
}
else if( x < y )
{
    y = y - x;
}
else
{
    // x and y should never be equal
    NEVER_GET_HERE;
}

Standard 20: Cases should be at the same level as the switch and indent the code one level beyond the case. The break statement is at the same indentation level as the code.

Standard 21: All switch statements shall have a default case. If all cases have been handled then the default code shall be NEVER_GET_HERE. If not then it shall be an empty statement.

switch(Variable)
{
case 1:
    // ... code ...
    break;

case 2:
    // ... code ...
    break;

default:
    NEVER_GET_HERE;
    break;
}

- OR -

switch(Variable)
{
case 1:
    // ... code ...
    break;

case 2:
    // ... code ...
    break;

default:
    ; // do nothing
    break;
}

Standard 22: Put the while in a do while statement on the same line as the closing brace.

á do { ++x; } while(x < y);

Preprocessor

Guideline 13: Preprocessor directives should be avoided whenever possible.

Standard 25: Multi-statement macros shall have one statement per line.

#define MULTIPLE_LINE_MACRO( s ) \
     ++(s); \
     (s) = ((s) % 3 ? ++(s) : (s))

Spaces

Standard 26: Do not use spaces in object de-references.

val = *pFoo; // ok
val = * pFoo; // wrong

Standard 27: When defining pointer types put asterix next to type with no spaces.

CClass* pFoo; // ok
CClass *pFoo; // wrong
CClass foo, *pFoo; // very wrong

Standard 28: Do not space between an unary operator and its operand, but do space the other side.

Standard 29: Balance spacing on either side of binary operators.

Standard 30: Do not space before separators ( semicolon, argument comma separator ) but do space the other side.

Standard 32: Balance spacing inside parenthesis.

Standard 34: Use blank lines before and after block comments.

Standard 35: Use vertical alignment to indicate association.

Standard 36: Use spaces, not tabs.

Rationale: Tab sizes vary between developers. When spaces are used, the alignment is maintained no matter where the file is edited.

Wrapping

Guideline 15: No line of code should extend beyond column 100.

Rationale: When the audience for the source and headers of a project may reach hundreds, if not more, readability and continuity become prime factors for comprehension. Additionally, in a multi-developer environment, the potential for disjoint style is personified with no restrictions on column length.

Standard 37: When wrapping lines, indent the continuation line past the current indent column.

int Val(2);
cout << "This is an example where I wrap "
     << Val
     << " lines of code" << endl;

Standard 38: Wrap assignments past the equal sign.

CObjectMapConstIterator Iterator =
        m_MapOfObjects.begin();

Standard 39: Wrap conditional expressions after the operators.

if(m_NameOfTheGame == gameName &&
   m_TimeBeingPlayed > Limit)
{
    // ...
}

Standard 40: Wrap for statements after the semi-colons.

Standard 41: Wrap long function signatures with one parameter per line.

void CClassMethod::setValues(
                               const Object& Object1,
                               const Object& Object2,
                               const STRING& Name,
                               const int Value,
                               ...
                            )
{
    ;
}

Naming Conventions

Standard 42: Spell words using correct English spelling. For the most part, avoid abbreviations. Abbreviations for common longwinded phases may be used as though they are normal words if the abbreviation is placed in the Glossary and the usage remains clear in the context.

Rationale: The semantics of a type are much better understood by the reader when they have names like "SpeakerCabinet" instead of "SpkCb".

Guideline 16: Make names clearly unique. Avoid similar-sounding names and similarly-spelled names.

int Count;
String Surname;
CObject Person;

- INSTEAD OF -

int x1;
String x2;
CObject x3;

Standard 43: Make all identifiers unique within a function.

Standard 44: Use mixed case to distinguish name segments instead of underscores.

CWellFormedObject WellFormedObject;   // ok
non_standard_form Wellformedobject;   // wrong

Standard 45: Types are all upper case and use underscores to separate name segments. (i.e. CURRENCY, BIG_CAR,STRING).

Standard 46: Variables and objects names that are data members of a class start with a 'm_' and followed by an upper case letter then mixed case.

class CFoo
{
public:
	  // ..
protected:
    NEW_TYPE m_NewType;
};

Standard 47: Variables and objects names that are arguments or locals start with an upper case letter and are mixed case thereafter. (i.e. NEW_TYPE NewType; ).

Standard 48: Pointer variable names are prefixed 'p' followed by an upper case letter.

Guideline 17: Only use short variable names when they have limited scope and obvious meaning. Beware of them causing confusion. Short variables may be lower case e.g. i in loops.

Standard 49: Use capital letters to begin new name segments within the name.

Guideline 18: Name functions with verb-noun (verb object) combinations. The first letter of functions should be upper case.

Guideline 19: Name variables and structures with noun, adjective noun combinations.

Standard 50: Accessor methods start with the word 'Get' and should be const.

Standard 51: Boolean accessor functions start with 'Is' and return bool.

Standard 52: Mutator procedures start with the word 'Put' and don't return values.

class CFoo
{
public:
    //
    // Accessor
    //
    const BSTR GetName(void) const;
    bool IsNameEmpty(void) const;

    //
    // Mutator
    //
    void PutName(const BSTR name);
protected:
    BSTR m_Name;
};

Standard 53: Factory instantiation functions start with the word 'Create'.

CThread*  CreateThread(void);

Standard 54: Factory destruction functions start with the word 'Destroy'.

void DestroyThread(CThread* threadToDestroy);

Files and Directories

Guideline 20: Name files like variables, describing the functions they contain. Long file names are encouraged.

Standard 56: Use .cpp and .h for class definition source and header file suffixes.

Standard 57: Any procedural code written should be compiled in C++ .

Rationale: C++ compilers provide much stricter type checking than C compilers. The stronger type checking is well worth using, even if the code does not take advantage of the object oriented features of C++ .

Guideline 23: Name directories like nested structures.

Usage

Guideline 24: There are no circumstances where goto is allowed.

Guideline 25: Avoid deep nesting of statements, parentheses, and structures.

Guideline 26: All assignments shall stand alone, unless a series of variables are being assigned to the same value.

Standard 58: Do not use comparisons in mathematical expressions.

numberOfDays = ( get_IsLeapYear() == TRUE ) + 28; // not OK

Guideline 59: All non-boolean comparison expressions should use a comparison operator. Do not use implicit != 0.

á

ASSERT(pObject != 0); // good

ASSERT(pObject); // bad

Guideline 27: Avoid assignment in comparisons, except where the alternative is significantly more complex.

Standard 60: Use explicit casting, instead of the compiler default.

DWORD UnsignedValue(0); REAL RealValue(3.7); BigValue = DWORD(RealValue);

Also note that the class operator overloads should be used as a preference for upcasting and downcasting:

class CFoo
{
public:
    operator DWORD(void) const
    {
        return DWORD(m_Value);
    }

    operator SHORT(void) const
    {
        return SHORT(m_Value);
    }

protected:
    REAL m_Value;
};

Guideline 28: Default to pre-increment and pre-decrement unless the post-increment/decrement operators are logically necessary.

Guideline 29: Minimize negative comparisons.

Guideline 30: Minimize use of the comma operator.

Conditionals

Guideline 31: Use if ( cond) ...else rather than conditional expressions ( ( cond) ? : ) if only to clarify the intended operation.

Guideline 32: Use nested if only to clarify the intended order of evaluation.

á
if( Foo() == true )
{
    if( Bar() == true )
    {
    }
}

-- VERSUS—

if( Foo() && Bar())
{
}

Standard 61: In a switch statement, make all cases independent by using break at the end of each. All switch statements should have a default. If all cases have been handled, then the default should never be NEVER_GET_HERE. This is also true for if...elseif...else blocks.

Standard 62: Use if...else for two alternative actions. Put the major action first. Exceptions to this standard are checks at the top of a function.

Loop Constructs

Guideline 33: Count for loops in ascending.

for(int x(0); x < ListSize; ++x)
{
    // code
}

Standard 63: Use for loops when the loop control needs initializing or recalculating; otherwise, use while.

// go backwards down array
x = ArrayOfThings.GetSize();
while(x-- > 0)
{
    Array[x].DoSomethingWithThing();
}

Standard 64: Use while( 1 ) to implement an infinite loop. Make its usage clear with comments.

Guideline 34: Be careful with the logic of do loops. Use do...while( !(...) ) to loop until a comparison becomes true.

Guideline 35: Minimize use of break in loops. Only use it for abnormal escape.

Guideline 36: Use continue sparingly. Clearly comment why continue is used.

Data

Guideline 38: Beware of operations with constants going out of range.

Standard 67: Use single-quoted characters for character constants, but never single-quote more than one character (or hex for non-printing).

Standard 68: Use sizeof rather than a constant.

Standard 69: Do not compare floating point numbers for equality.

Standard 70: Assign to all data members in operator=.

Standard 71: Check for assignment to this in operator=. If assignment to this is attempted, simply return from the function.

MyClassRef MyClass::operator=(MyClassCref aRef)
{
    if( this != &aRef )
    {
        // do the assignment
        ...
    }
    else
    {
        ; // do nothing
    }
    return *this;
}

Standard 72: Make sure operator= invokes any parents' operator=, except with virtual inheritance.

Initialization

Standard 77: Explicitly initialize static data.

Standard 78: Initialize all variables at the time they are declared to the appropriate value. If the value is not yet known, initialize pointers to simple types to zero or NULL.

Standard 79: List members in a constructor initialization list in order in which they are declared in the class header.

Standard 80: Check for empty pointer or handle by comparison with NULL.

Declaration

Guideline 40: All data should be defined as close as possible to where it is needed.

Guideline 41: Use floating point numbers only where necessary.

Guideline 42: Do not use global data. Consider putting global information in the context of a static class.

Guideline 43: Do not use unions.

Guideline 44: Do not use bit structures.

Programming

Guideline 45: Make sure interface definitions are clear and sufficient.

Guideline 46: Defend against system, program and user errors. Heavy use of assertions and exceptions are encouraged.

Guideline 47: Enable the user and the maintainer to find sufficient information to understand an error. Include enough diagnostic information to give an accurate picture of why the error occurred.

Guideline 48: Do not use arbitrary, predefined limits( e.g. on symbol table entries, user names, file names).

Standard 87: Use the same form in corresponding calls to new and delete (i.e. new CFoo uses delete pFoo and new CFoo[100] uses delete [] fooArray.

Guideline 50: Know what C++ silently creates and calls (e.g. default constructor, copy constructor, assignment operator, address-of operators(const and not), and the destructor for a derived class where the base class's destructor is defined.)

Standard 88: Ensure that objects (both simple and class) are initialized before they are used.

Standard 83: Eradicate all compiler warnings. Set the compiler to the highest warning level. Any unavoidable warnings must be explicitly commented in the code. Unavoidable compiler warnings should be extremely rare.

Class and Functions

Guideline 51: Strive for class interfaces that are complete and minimal.

Guideline 52: The programmer should only have to look at the .h file to use a class.

Guideline 53: Do not put data members in the public interface.

Standard 90: Pass and return objects be reference instead of value whenever possible.

Standard 91: If the passed object is not going to be modified then pass it as a const reference.

Standard 92: The keyword class will appear in the left most column. If declaring the class in the scope of a namespace, then class will be indented appropriately.

Standard 93: The member access controls appear flush with the class keyword.

Standard 94: Access controls that have no members may be omitted.

Standard 95: Access controls appear in the following order

public: // Public method declarations

protected: // Protected method declarations

private: // Private method declarations

protected: // Protected class data members

private: // Private class data members

comments here are for clarification.

Standard 96: The virtual or static declarations appear in the first indentation level from the class declaration.

Standard 97: The return type of a class method or the storage type of a class data member appear after the first tab position beyond the space were virtual applied.

Standard 98: Method identifiers follow the return type and should be reasonably lined with other method declarations.

Standard 99: In each access control group for methods, Constructors are followed by destructor, followed by operator overloads, followed by accessors followed by mutators.

class CMyClass
{
public:
    /// Default constructor
    CMyClass(void)

    /**
    Copy constructor
    @param Object constant reference
    */
    CMyClass(const Object& init);

    /// Destructor
    virtual ~CMyClass(void);

    /**
    Equality operator overload
    @param CMyClass constant reference
    @return bool - true if equal, false otherwise
    */

    bool operator==(const CMyClass& copy);

    //
    // Accessors
    //
á
    /**
    Get the number of MyClass instantiations.
    @return Int const reference to count
    */
á    static const INT GetInstanceCount(void);

    /**
    Return the object data member
    @return Object const
    reference
    */

    const CObject& GetObject(void) const;

    //
    // Mutators
    //

    /**
    Sets the something thing
    @param Something const reference
    */

    virtual void PutSomething(const CSomething& something);

protected:
    /// Copy never allowed
    CMyClass(const CMyClass& ) throw(Assertion)
    {
        NEVER_GET_HERE;
    }

    /// Assignment operator denied
    CMyClassRef operator=( const CMyClass& ) throw(Assertion)
    {
		    NEVER_GET_HERE;
        return *this;
    }

private:
    // No private methods

protected:
    // No public data members

private:
    /// Class instance counter
    static int m_InstanceCount;
};

Guideline 54: Don't return a reference, or pointer, when you must return an object, and don't return an object when you mean a reference.

Guideline 55: Avoid overloading on a pointer and a numerical type. (i.e. Foo(char *) vs. Foo(int) - a call to Foo(0) is ambiguous).

Standard 100: Do not return handles to internal data from const member functions. If a handle must be returned, make it const.

Standard 101: Avoid member functions that return pointers or references to members less accessible than themselves. Use const !

Standard 102: Never return a reference to a local object or a de-referenced pointer initialized by new within the function.

Rationale: Obviously, when a functions ends, the local object goes out of scope, and the reference is no longer valid. One might attempt to NEW the object in the function instead, but then who would call the corresponding DELETE?

Standard 103: Use enums for integral class constants.

Guideline 57: Use inlining judiciously.

Guideline 58: Inlines cause code bloat, slow down compile times, eat up name space, and not all compilers handle them the same way.

Inheritance

Guideline 59: Make sure public inheritance models 'is-a'.

Guideline 60: Differentiate between inheritance of the interface and of the implementation, and prefer delegation to implementation inheritance.

Rationale: Inheritance of the interface only is forced by making a function pure virtual- its implementation must be defined by the derived class. Inheritance of implementation occurs when the function is declared as simple virtual-derived classes may or may not override the implementation.

Standard 106: Never redefine an inherited non-virtual function.

Standard 107: Never redefine an inherited default parameter value.

Guideline 61: Use private inheritance judiciously.

Guideline 62: Differentiate between inheritance and templates.

Rationale: If the type of the object being manipulated does not affect the behavior or the class, then a template will do. However, if the type of the object DOES affect the behavior, then virtual functions should be used through inheritance.

Object-Oriented Considerations

Standard 109: Factor our common code into an ancestor.

Guideline 63: Encapsulate external code within an operation or class.

Guideline 64: Keep member functions small, coherent and consistent.

Guideline 65: Separate policy member functions (e.g. error and status checkers) from implementation member functions (computational).

Standard 110: Do not use indirect function calls unless absolutely necessary.

Standard 111: Write member functions for all combinations of input conditions. Avoid using modes to distinguish between conditions. Use member function overloading instead.

Standard 112: Avoid case statements on object type; use member functions instead.

Standard 113: Keep internal class structure hidden from other classes. Do not use global or public data.

Standard 114: Do not traverse multiple links or member functions in a single statement. Invoke each member function via a temporary pointer or reference.

Standard 115: Use const wherever a function, parameter or return value will not change.

Guideline 116: All accessor functions should be const.

Error Handling

Standard 117: Use exceptions rather than returning a failure status. However do not use exceptions for conditions that are expected to occur frequently.

Standard 118: Use assertions (ASSERT, VERIFY, NEVER_GET_HERE) liberally.

File Layout

Guideline 66: Use functional cohesion to group similar items.

Guideline 67: Source files may be split up along boundaries between class administrator, accessor, mutator and provider functions.

Standard 123: A class shall have a single header file.

Guideline 68: Layout data files to reflect the systems they serve.

Standard 124: Do not reserve memory in header files.

Standard 125: Minimize header file interdependence.

Guideline 69: Keep function length in code files to within one or two pages (100 lines).

Guideline 70: Keep modules small. Each module should be functionally cohesive and should be as small as possible. Modules should not exceed 10-15 pages in length.

Guideline 71: Classes with a large number of functions should break the implementation into several .CPP files. These files should be functionally cohesive.

Header File Layout

Standard 126: All headers must be wrapped to prevent multiple inclusion.

#if !defined(__MYHEADER_H__)
#define __MYHEADER_H__

...

#endif // __MYHEADER_H__

-OR-

#pragma once

Standard 127: The wrapper must be the name of the file, prefixed with a double underscore __ and followed by _H__. (i.e. __COMMON_H__).

Standard 128: public, protected and private line appear in column 0 within a class definition.

Standard 129: Types, returns, member names, functions must be lined up consistently in header.

Standard 130: Trailing comments must be aligned within the module.

Bibliography

Grady Booch.

Object Oriented Analysis and Design With Applications.

Benjamin/Cummings, Redwood City, CA, 2nd edition, 1994.

TheáCorelinux Consortium.

The Corelinux C++ Coding Standards.

The Corelinux Consortium, 1.3 edition, May 2000a.

http://corelinux.sourceforge.net/cppstnd.php.

TheáCorelinux Consortium.

The Corelinux Object Oriented Design Standards.

The Corelinux Consortium, 1.3 edition, May 2000b.

PhillipáB. Crosby.

Quality Is Free.

McGraw-Hill, New York, NY., 10020, 1976.

FSF.

GNU Autoconf Manual.

FSF, 2.13 edition, 1999.

FSF.

GNU Automake Manual.

FSF, 1.4 edition, 2000a.

FSF.

GNU Libtool Manual.

FSF, 1.3.4 edition, 2000b.

D.E. Knuth.

Structured programming with goto's.

ACM Computing Surveys, Vol 6(No. 4), December 1974.

Bertrand Meyer.

Object Oriented Software Construction.

Prentice Hall, Englewood Cliffs, NJ, 1988.

Inc. Taligent.

The Taligent Guide to Well-Mannered Object-Oriented Programs.

Taligent Inc., Cupertino, CA., 1994.

Frank V. Castellucci 2001-01-01

Modifications John Adcock 2001-07-13

á
á